"""
py_trees.behaviours.Periodic(name:str, n:int)
参数:
    前n个:Running
    中n+1个:Success
    后n+1个:Failure
    循环
"""

#!/usr/bin/env python
import time
import py_trees


def pre_tick_handler(behaviour_tree: py_trees.trees.BehaviourTree) -> None:
    """Generate a simple pre-tick banner printing to stdout."""
    print("--------- Run %s ---------" % behaviour_tree.count)


class PeriodicSuccess(py_trees.behaviours.Periodic):
    def __init__(self) -> None:
        super().__init__(name="Periodic", n=3)
        self.record_count = 0
        self.Running_List: list = []
        self.Success_List: list = []
        self.Failure_List: list = []

    def update(self) -> py_trees.common.Status:
        status = super().update()
        if status == py_trees.common.Status.RUNNING:
            self.Running_List.append(self.record_count)
        elif status == py_trees.common.Status.SUCCESS:
            self.Success_List.append(self.record_count)
        elif status == py_trees.common.Status.FAILURE:
            self.Failure_List.append(self.record_count)
        print("PeriodicSuccess.update() -> {}, count:{}, record_count:{}".format(status, self.count, self.record_count))
        self.record_count += 1
        if self.record_count >= 19 :
            self.show_result()
        return status

    def show_result(self):
        self.logger.warning(f"Running toal: {len(self.Running_List)}, {self.Running_List}")
        self.logger.warning(f"Success toal: {len(self.Success_List)}, {self.Success_List}")
        self.logger.warning(f"Failure toal: {len(self.Failure_List)}, {self.Failure_List}")


def create_tree() -> py_trees.behaviour.Behaviour:
    root_sequence = py_trees.composites.Sequence(name="test_Periodic", memory=True)
    periodic_task = PeriodicSuccess()
    root_sequence.add_child(periodic_task)
    return root_sequence


def main() -> None:
    tree = create_tree()
    py_trees.display.render_dot_tree(tree, with_blackboard_variables=True)
    behaviour_tree = py_trees.trees.BehaviourTree(tree)
    behaviour_tree.add_pre_tick_handler(pre_tick_handler)

    count = 20
    while count > 0:
        try:
            behaviour_tree.tick()
            time.sleep(0.5)
        except KeyboardInterrupt:
            break
        count -= 1

    print("\n")


if __name__ == "__main__":
    main()


""" 测试结果
PeriodicSuccess.update() -> Status.FAILURE, count:0, record_count:19
[ WARN] Periodic             : Running toal: 7, [0, 1, 2, 11, 12, 13, 14]
[ WARN] Periodic             : Success toal: 8, [3, 4, 5, 6, 15, 16, 17, 18]
[ WARN] Periodic             : Failure toal: 5, [7, 8, 9, 10, 19]
"""
